home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-desktop-9.10-i386-PL.iso / casper / filesystem.squashfs / usr / lib / python2.6 / doctest.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2009-11-11  |  80KB  |  2,281 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. '''Module doctest -- a framework for running examples in docstrings.
  5.  
  6. In simplest use, end each module M to be tested with:
  7.  
  8. def _test():
  9.     import doctest
  10.     doctest.testmod()
  11.  
  12. if __name__ == "__main__":
  13.     _test()
  14.  
  15. Then running the module as a script will cause the examples in the
  16. docstrings to get executed and verified:
  17.  
  18. python M.py
  19.  
  20. This won\'t display anything unless an example fails, in which case the
  21. failing example(s) and the cause(s) of the failure(s) are printed to stdout
  22. (why not stderr? because stderr is a lame hack <0.2 wink>), and the final
  23. line of output is "Test failed.".
  24.  
  25. Run it with the -v switch instead:
  26.  
  27. python M.py -v
  28.  
  29. and a detailed report of all examples tried is printed to stdout, along
  30. with assorted summaries at the end.
  31.  
  32. You can force verbose mode by passing "verbose=True" to testmod, or prohibit
  33. it by passing "verbose=False".  In either of those cases, sys.argv is not
  34. examined by testmod.
  35.  
  36. There are a variety of other ways to run doctests, including integration
  37. with the unittest framework, and support for running non-Python text
  38. files containing doctests.  There are also many ways to override parts
  39. of doctest\'s default behaviors.  See the Library Reference Manual for
  40. details.
  41. '''
  42. __docformat__ = 'reStructuredText en'
  43. __all__ = [
  44.     'register_optionflag',
  45.     'DONT_ACCEPT_TRUE_FOR_1',
  46.     'DONT_ACCEPT_BLANKLINE',
  47.     'NORMALIZE_WHITESPACE',
  48.     'ELLIPSIS',
  49.     'SKIP',
  50.     'IGNORE_EXCEPTION_DETAIL',
  51.     'COMPARISON_FLAGS',
  52.     'REPORT_UDIFF',
  53.     'REPORT_CDIFF',
  54.     'REPORT_NDIFF',
  55.     'REPORT_ONLY_FIRST_FAILURE',
  56.     'REPORTING_FLAGS',
  57.     'Example',
  58.     'DocTest',
  59.     'DocTestParser',
  60.     'DocTestFinder',
  61.     'DocTestRunner',
  62.     'OutputChecker',
  63.     'DocTestFailure',
  64.     'UnexpectedException',
  65.     'DebugRunner',
  66.     'testmod',
  67.     'testfile',
  68.     'run_docstring_examples',
  69.     'Tester',
  70.     'DocTestSuite',
  71.     'DocFileSuite',
  72.     'set_unittest_reportflags',
  73.     'script_from_examples',
  74.     'testsource',
  75.     'debug_src',
  76.     'debug']
  77. import __future__
  78. import sys
  79. import traceback
  80. import inspect
  81. import linecache
  82. import os
  83. import re
  84. import unittest
  85. import difflib
  86. import pdb
  87. import tempfile
  88. import warnings
  89. from StringIO import StringIO
  90. from collections import namedtuple
  91. TestResults = namedtuple('TestResults', 'failed attempted')
  92. OPTIONFLAGS_BY_NAME = { }
  93.  
  94. def register_optionflag(name):
  95.     return OPTIONFLAGS_BY_NAME.setdefault(name, 1 << len(OPTIONFLAGS_BY_NAME))
  96.  
  97. DONT_ACCEPT_TRUE_FOR_1 = register_optionflag('DONT_ACCEPT_TRUE_FOR_1')
  98. DONT_ACCEPT_BLANKLINE = register_optionflag('DONT_ACCEPT_BLANKLINE')
  99. NORMALIZE_WHITESPACE = register_optionflag('NORMALIZE_WHITESPACE')
  100. ELLIPSIS = register_optionflag('ELLIPSIS')
  101. SKIP = register_optionflag('SKIP')
  102. IGNORE_EXCEPTION_DETAIL = register_optionflag('IGNORE_EXCEPTION_DETAIL')
  103. COMPARISON_FLAGS = DONT_ACCEPT_TRUE_FOR_1 | DONT_ACCEPT_BLANKLINE | NORMALIZE_WHITESPACE | ELLIPSIS | SKIP | IGNORE_EXCEPTION_DETAIL
  104. REPORT_UDIFF = register_optionflag('REPORT_UDIFF')
  105. REPORT_CDIFF = register_optionflag('REPORT_CDIFF')
  106. REPORT_NDIFF = register_optionflag('REPORT_NDIFF')
  107. REPORT_ONLY_FIRST_FAILURE = register_optionflag('REPORT_ONLY_FIRST_FAILURE')
  108. REPORTING_FLAGS = REPORT_UDIFF | REPORT_CDIFF | REPORT_NDIFF | REPORT_ONLY_FIRST_FAILURE
  109. BLANKLINE_MARKER = '<BLANKLINE>'
  110. ELLIPSIS_MARKER = '...'
  111.  
  112. def _extract_future_flags(globs):
  113.     '''
  114.     Return the compiler-flags associated with the future features that
  115.     have been imported into the given namespace (globs).
  116.     '''
  117.     flags = 0
  118.     for fname in __future__.all_feature_names:
  119.         feature = globs.get(fname, None)
  120.         if feature is getattr(__future__, fname):
  121.             flags |= feature.compiler_flag
  122.             continue
  123.     
  124.     return flags
  125.  
  126.  
  127. def _normalize_module(module, depth = 2):
  128.     '''
  129.     Return the module specified by `module`.  In particular:
  130.       - If `module` is a module, then return module.
  131.       - If `module` is a string, then import and return the
  132.         module with that name.
  133.       - If `module` is None, then return the calling module.
  134.         The calling module is assumed to be the module of
  135.         the stack frame at the given depth in the call stack.
  136.     '''
  137.     if inspect.ismodule(module):
  138.         return module
  139.     if isinstance(module, (str, unicode)):
  140.         return __import__(module, globals(), locals(), [
  141.             '*'])
  142.     if module is None:
  143.         return sys.modules[sys._getframe(depth).f_globals['__name__']]
  144.     raise TypeError('Expected a module, string, or None')
  145.  
  146.  
  147. def _load_testfile(filename, package, module_relative):
  148.     if module_relative:
  149.         package = _normalize_module(package, 3)
  150.         filename = _module_relative_path(package, filename)
  151.         if hasattr(package, '__loader__'):
  152.             if hasattr(package.__loader__, 'get_data'):
  153.                 file_contents = package.__loader__.get_data(filename)
  154.                 return (file_contents.replace(os.linesep, '\n'), filename)
  155.         
  156.     
  157.     return (open(filename).read(), filename)
  158.  
  159.  
  160. def _indent(s, indent = 4):
  161.     '''
  162.     Add the given number of space characters to the beginning every
  163.     non-blank line in `s`, and return the result.
  164.     '''
  165.     return re.sub('(?m)^(?!$)', indent * ' ', s)
  166.  
  167.  
  168. def _exception_traceback(exc_info):
  169.     '''
  170.     Return a string containing a traceback message for the given
  171.     exc_info tuple (as returned by sys.exc_info()).
  172.     '''
  173.     excout = StringIO()
  174.     (exc_type, exc_val, exc_tb) = exc_info
  175.     traceback.print_exception(exc_type, exc_val, exc_tb, file = excout)
  176.     return excout.getvalue()
  177.  
  178.  
  179. class _SpoofOut(StringIO):
  180.     
  181.     def getvalue(self):
  182.         result = StringIO.getvalue(self)
  183.         if result and not result.endswith('\n'):
  184.             result += '\n'
  185.         
  186.         if hasattr(self, 'softspace'):
  187.             del self.softspace
  188.         
  189.         return result
  190.  
  191.     
  192.     def truncate(self, size = None):
  193.         StringIO.truncate(self, size)
  194.         if hasattr(self, 'softspace'):
  195.             del self.softspace
  196.         
  197.  
  198.  
  199.  
  200. def _ellipsis_match(want, got):
  201.     """
  202.     Essentially the only subtle case:
  203.     >>> _ellipsis_match('aa...aa', 'aaa')
  204.     False
  205.     """
  206.     if ELLIPSIS_MARKER not in want:
  207.         return want == got
  208.     ws = want.split(ELLIPSIS_MARKER)
  209.     if not len(ws) >= 2:
  210.         raise AssertionError
  211.     startpos = 0
  212.     endpos = len(got)
  213.     w = ws[0]
  214.     if w:
  215.         if got.startswith(w):
  216.             startpos = len(w)
  217.             del ws[0]
  218.         else:
  219.             return False
  220.     got.startswith(w)
  221.     w = ws[-1]
  222.     if w:
  223.         if got.endswith(w):
  224.             endpos -= len(w)
  225.             del ws[-1]
  226.         else:
  227.             return False
  228.     got.endswith(w)
  229.     if startpos > endpos:
  230.         return False
  231.     for w in ws:
  232.         startpos = got.find(w, startpos, endpos)
  233.         if startpos < 0:
  234.             return False
  235.         startpos += len(w)
  236.     
  237.     return True
  238.  
  239.  
  240. def _comment_line(line):
  241.     '''Return a commented form of the given line'''
  242.     line = line.rstrip()
  243.     if line:
  244.         return '# ' + line
  245.     return '#'
  246.  
  247.  
  248. class _OutputRedirectingPdb(pdb.Pdb):
  249.     '''
  250.     A specialized version of the python debugger that redirects stdout
  251.     to a given stream when interacting with the user.  Stdout is *not*
  252.     redirected when traced code is executed.
  253.     '''
  254.     
  255.     def __init__(self, out):
  256.         self._OutputRedirectingPdb__out = out
  257.         self._OutputRedirectingPdb__debugger_used = False
  258.         pdb.Pdb.__init__(self, stdout = out)
  259.  
  260.     
  261.     def set_trace(self, frame = None):
  262.         self._OutputRedirectingPdb__debugger_used = True
  263.         if frame is None:
  264.             frame = sys._getframe().f_back
  265.         
  266.         pdb.Pdb.set_trace(self, frame)
  267.  
  268.     
  269.     def set_continue(self):
  270.         if self._OutputRedirectingPdb__debugger_used:
  271.             pdb.Pdb.set_continue(self)
  272.         
  273.  
  274.     
  275.     def trace_dispatch(self, *args):
  276.         save_stdout = sys.stdout
  277.         sys.stdout = self._OutputRedirectingPdb__out
  278.         
  279.         try:
  280.             return pdb.Pdb.trace_dispatch(self, *args)
  281.         finally:
  282.             sys.stdout = save_stdout
  283.  
  284.  
  285.  
  286.  
  287. def _module_relative_path(module, path):
  288.     if not inspect.ismodule(module):
  289.         raise TypeError, 'Expected a module: %r' % module
  290.     inspect.ismodule(module)
  291.     if path.startswith('/'):
  292.         raise ValueError, 'Module-relative files may not have absolute paths'
  293.     path.startswith('/')
  294.     if hasattr(module, '__file__'):
  295.         basedir = os.path.split(module.__file__)[0]
  296.     elif module.__name__ == '__main__':
  297.         if len(sys.argv) > 0 and sys.argv[0] != '':
  298.             basedir = os.path.split(sys.argv[0])[0]
  299.         else:
  300.             basedir = os.curdir
  301.     else:
  302.         raise ValueError("Can't resolve paths relative to the module " + module + ' (it has no __file__)')
  303.     return hasattr(module, '__file__').path.join(basedir, *path.split('/'))
  304.  
  305.  
  306. class Example:
  307.     """
  308.     A single doctest example, consisting of source code and expected
  309.     output.  `Example` defines the following attributes:
  310.  
  311.       - source: A single Python statement, always ending with a newline.
  312.         The constructor adds a newline if needed.
  313.  
  314.       - want: The expected output from running the source code (either
  315.         from stdout, or a traceback in case of exception).  `want` ends
  316.         with a newline unless it's empty, in which case it's an empty
  317.         string.  The constructor adds a newline if needed.
  318.  
  319.       - exc_msg: The exception message generated by the example, if
  320.         the example is expected to generate an exception; or `None` if
  321.         it is not expected to generate an exception.  This exception
  322.         message is compared against the return value of
  323.         `traceback.format_exception_only()`.  `exc_msg` ends with a
  324.         newline unless it's `None`.  The constructor adds a newline
  325.         if needed.
  326.  
  327.       - lineno: The line number within the DocTest string containing
  328.         this Example where the Example begins.  This line number is
  329.         zero-based, with respect to the beginning of the DocTest.
  330.  
  331.       - indent: The example's indentation in the DocTest string.
  332.         I.e., the number of space characters that preceed the
  333.         example's first prompt.
  334.  
  335.       - options: A dictionary mapping from option flags to True or
  336.         False, which is used to override default options for this
  337.         example.  Any option flags not contained in this dictionary
  338.         are left at their default value (as specified by the
  339.         DocTestRunner's optionflags).  By default, no options are set.
  340.     """
  341.     
  342.     def __init__(self, source, want, exc_msg = None, lineno = 0, indent = 0, options = None):
  343.         if not source.endswith('\n'):
  344.             source += '\n'
  345.         
  346.         if want and not want.endswith('\n'):
  347.             want += '\n'
  348.         
  349.         if exc_msg is not None and not exc_msg.endswith('\n'):
  350.             exc_msg += '\n'
  351.         
  352.         self.source = source
  353.         self.want = want
  354.         self.lineno = lineno
  355.         self.indent = indent
  356.         if options is None:
  357.             options = { }
  358.         
  359.         self.options = options
  360.         self.exc_msg = exc_msg
  361.  
  362.  
  363.  
  364. class DocTest:
  365.     '''
  366.     A collection of doctest examples that should be run in a single
  367.     namespace.  Each `DocTest` defines the following attributes:
  368.  
  369.       - examples: the list of examples.
  370.  
  371.       - globs: The namespace (aka globals) that the examples should
  372.         be run in.
  373.  
  374.       - name: A name identifying the DocTest (typically, the name of
  375.         the object whose docstring this DocTest was extracted from).
  376.  
  377.       - filename: The name of the file that this DocTest was extracted
  378.         from, or `None` if the filename is unknown.
  379.  
  380.       - lineno: The line number within filename where this DocTest
  381.         begins, or `None` if the line number is unavailable.  This
  382.         line number is zero-based, with respect to the beginning of
  383.         the file.
  384.  
  385.       - docstring: The string that the examples were extracted from,
  386.         or `None` if the string is unavailable.
  387.     '''
  388.     
  389.     def __init__(self, examples, globs, name, filename, lineno, docstring):
  390.         """
  391.         Create a new DocTest containing the given examples.  The
  392.         DocTest's globals are initialized with a copy of `globs`.
  393.         """
  394.         if not not isinstance(examples, basestring):
  395.             raise AssertionError, 'DocTest no longer accepts str; use DocTestParser instead'
  396.         self.examples = examples
  397.         self.docstring = docstring
  398.         self.globs = globs.copy()
  399.         self.name = name
  400.         self.filename = filename
  401.         self.lineno = lineno
  402.  
  403.     
  404.     def __repr__(self):
  405.         if len(self.examples) == 0:
  406.             examples = 'no examples'
  407.         elif len(self.examples) == 1:
  408.             examples = '1 example'
  409.         else:
  410.             examples = '%d examples' % len(self.examples)
  411.         return '<DocTest %s from %s:%s (%s)>' % (self.name, self.filename, self.lineno, examples)
  412.  
  413.     
  414.     def __cmp__(self, other):
  415.         if not isinstance(other, DocTest):
  416.             return -1
  417.         return cmp((self.name, self.filename, self.lineno, id(self)), (other.name, other.filename, other.lineno, id(other)))
  418.  
  419.  
  420.  
  421. class DocTestParser:
  422.     '''
  423.     A class used to parse strings containing doctest examples.
  424.     '''
  425.     _EXAMPLE_RE = re.compile('\n        # Source consists of a PS1 line followed by zero or more PS2 lines.\n        (?P<source>\n            (?:^(?P<indent> [ ]*) >>>    .*)    # PS1 line\n            (?:\\n           [ ]*  \\.\\.\\. .*)*)  # PS2 lines\n        \\n?\n        # Want consists of any non-blank lines that do not start with PS1.\n        (?P<want> (?:(?![ ]*$)    # Not a blank line\n                     (?![ ]*>>>)  # Not a line starting with PS1\n                     .*$\\n?       # But any other line\n                  )*)\n        ', re.MULTILINE | re.VERBOSE)
  426.     _EXCEPTION_RE = re.compile("\n        # Grab the traceback header.  Different versions of Python have\n        # said different things on the first traceback line.\n        ^(?P<hdr> Traceback\\ \\(\n            (?: most\\ recent\\ call\\ last\n            |   innermost\\ last\n            ) \\) :\n        )\n        \\s* $                # toss trailing whitespace on the header.\n        (?P<stack> .*?)      # don't blink: absorb stuff until...\n        ^ (?P<msg> \\w+ .*)   #     a line *starts* with alphanum.\n        ", re.VERBOSE | re.MULTILINE | re.DOTALL)
  427.     _IS_BLANK_OR_COMMENT = re.compile('^[ ]*(#.*)?$').match
  428.     
  429.     def parse(self, string, name = '<string>'):
  430.         '''
  431.         Divide the given string into examples and intervening text,
  432.         and return them as a list of alternating Examples and strings.
  433.         Line numbers for the Examples are 0-based.  The optional
  434.         argument `name` is a name identifying this string, and is only
  435.         used for error messages.
  436.         '''
  437.         string = string.expandtabs()
  438.         min_indent = self._min_indent(string)
  439.         output = []
  440.         (charno, lineno) = (0, 0)
  441.         for m in self._EXAMPLE_RE.finditer(string):
  442.             output.append(string[charno:m.start()])
  443.             lineno += string.count('\n', charno, m.start())
  444.             (source, options, want, exc_msg) = self._parse_example(m, name, lineno)
  445.             if not self._IS_BLANK_OR_COMMENT(source):
  446.                 output.append(Example(source, want, exc_msg, lineno = lineno, indent = min_indent + len(m.group('indent')), options = options))
  447.             
  448.             lineno += string.count('\n', m.start(), m.end())
  449.             charno = m.end()
  450.         
  451.         output.append(string[charno:])
  452.         return output
  453.  
  454.     
  455.     def get_doctest(self, string, globs, name, filename, lineno):
  456.         '''
  457.         Extract all doctest examples from the given string, and
  458.         collect them into a `DocTest` object.
  459.  
  460.         `globs`, `name`, `filename`, and `lineno` are attributes for
  461.         the new `DocTest` object.  See the documentation for `DocTest`
  462.         for more information.
  463.         '''
  464.         return DocTest(self.get_examples(string, name), globs, name, filename, lineno, string)
  465.  
  466.     
  467.     def get_examples(self, string, name = '<string>'):
  468.         '''
  469.         Extract all doctest examples from the given string, and return
  470.         them as a list of `Example` objects.  Line numbers are
  471.         0-based, because it\'s most common in doctests that nothing
  472.         interesting appears on the same line as opening triple-quote,
  473.         and so the first interesting line is called "line 1" then.
  474.  
  475.         The optional argument `name` is a name identifying this
  476.         string, and is only used for error messages.
  477.         '''
  478.         return _[1]
  479.  
  480.     
  481.     def _parse_example(self, m, name, lineno):
  482.         """
  483.         Given a regular expression match from `_EXAMPLE_RE` (`m`),
  484.         return a pair `(source, want)`, where `source` is the matched
  485.         example's source code (with prompts and indentation stripped);
  486.         and `want` is the example's expected output (with indentation
  487.         stripped).
  488.  
  489.         `name` is the string's name, and `lineno` is the line number
  490.         where the example starts; both are used for error messages.
  491.         """
  492.         indent = len(m.group('indent'))
  493.         source_lines = m.group('source').split('\n')
  494.         self._check_prompt_blank(source_lines, indent, name, lineno)
  495.         self._check_prefix(source_lines[1:], ' ' * indent + '.', name, lineno)
  496.         source = []([ sl[indent + 4:] for sl in source_lines ])
  497.         want = m.group('want')
  498.         want_lines = want.split('\n')
  499.         self._check_prefix(want_lines, ' ' * indent, name, lineno + len(source_lines))
  500.         want = []([ wl[indent:] for wl in want_lines ])
  501.         m = self._EXCEPTION_RE.match(want)
  502.         options = self._find_options(source, name, lineno)
  503.         return (source, options, want, exc_msg)
  504.  
  505.     _OPTION_DIRECTIVE_RE = re.compile('#\\s*doctest:\\s*([^\\n\\\'"]*)$', re.MULTILINE)
  506.     
  507.     def _find_options(self, source, name, lineno):
  508.         """
  509.         Return a dictionary containing option overrides extracted from
  510.         option directives in the given source string.
  511.  
  512.         `name` is the string's name, and `lineno` is the line number
  513.         where the example starts; both are used for error messages.
  514.         """
  515.         options = { }
  516.         for m in self._OPTION_DIRECTIVE_RE.finditer(source):
  517.             option_strings = m.group(1).replace(',', ' ').split()
  518.             for option in option_strings:
  519.                 if option[0] not in '+-' or option[1:] not in OPTIONFLAGS_BY_NAME:
  520.                     raise ValueError('line %r of the doctest for %s has an invalid option: %r' % (lineno + 1, name, option))
  521.                 option[1:] not in OPTIONFLAGS_BY_NAME
  522.                 flag = OPTIONFLAGS_BY_NAME[option[1:]]
  523.                 options[flag] = option[0] == '+'
  524.             
  525.         
  526.         if options and self._IS_BLANK_OR_COMMENT(source):
  527.             raise ValueError('line %r of the doctest for %s has an option directive on a line with no example: %r' % (lineno, name, source))
  528.         self._IS_BLANK_OR_COMMENT(source)
  529.         return options
  530.  
  531.     _INDENT_RE = re.compile('^([ ]*)(?=\\S)', re.MULTILINE)
  532.     
  533.     def _min_indent(self, s):
  534.         '''Return the minimum indentation of any non-blank line in `s`'''
  535.         indents = [ len(indent) for indent in self._INDENT_RE.findall(s) ]
  536.         if len(indents) > 0:
  537.             return min(indents)
  538.         return 0
  539.  
  540.     
  541.     def _check_prompt_blank(self, lines, indent, name, lineno):
  542.         '''
  543.         Given the lines of a source string (including prompts and
  544.         leading indentation), check to make sure that every prompt is
  545.         followed by a space character.  If any line is not followed by
  546.         a space character, then raise ValueError.
  547.         '''
  548.         for i, line in enumerate(lines):
  549.             if len(line) >= indent + 4 and line[indent + 3] != ' ':
  550.                 raise ValueError('line %r of the docstring for %s lacks blank after %s: %r' % (lineno + i + 1, name, line[indent:indent + 3], line))
  551.             line[indent + 3] != ' '
  552.         
  553.  
  554.     
  555.     def _check_prefix(self, lines, prefix, name, lineno):
  556.         '''
  557.         Check that every line in the given list starts with the given
  558.         prefix; if any line does not, then raise a ValueError.
  559.         '''
  560.         for i, line in enumerate(lines):
  561.             if line and not line.startswith(prefix):
  562.                 raise ValueError('line %r of the docstring for %s has inconsistent leading whitespace: %r' % (lineno + i + 1, name, line))
  563.             not line.startswith(prefix)
  564.         
  565.  
  566.  
  567.  
  568. class DocTestFinder:
  569.     '''
  570.     A class used to extract the DocTests that are relevant to a given
  571.     object, from its docstring and the docstrings of its contained
  572.     objects.  Doctests can currently be extracted from the following
  573.     object types: modules, functions, classes, methods, staticmethods,
  574.     classmethods, and properties.
  575.     '''
  576.     
  577.     def __init__(self, verbose = False, parser = DocTestParser(), recurse = True, exclude_empty = True):
  578.         '''
  579.         Create a new doctest finder.
  580.  
  581.         The optional argument `parser` specifies a class or
  582.         function that should be used to create new DocTest objects (or
  583.         objects that implement the same interface as DocTest).  The
  584.         signature for this factory function should match the signature
  585.         of the DocTest constructor.
  586.  
  587.         If the optional argument `recurse` is false, then `find` will
  588.         only examine the given object, and not any contained objects.
  589.  
  590.         If the optional argument `exclude_empty` is false, then `find`
  591.         will include tests for objects with empty docstrings.
  592.         '''
  593.         self._parser = parser
  594.         self._verbose = verbose
  595.         self._recurse = recurse
  596.         self._exclude_empty = exclude_empty
  597.  
  598.     
  599.     def find(self, obj, name = None, module = None, globs = None, extraglobs = None):
  600.         """
  601.         Return a list of the DocTests that are defined by the given
  602.         object's docstring, or by any of its contained objects'
  603.         docstrings.
  604.  
  605.         The optional parameter `module` is the module that contains
  606.         the given object.  If the module is not specified or is None, then
  607.         the test finder will attempt to automatically determine the
  608.         correct module.  The object's module is used:
  609.  
  610.             - As a default namespace, if `globs` is not specified.
  611.             - To prevent the DocTestFinder from extracting DocTests
  612.               from objects that are imported from other modules.
  613.             - To find the name of the file containing the object.
  614.             - To help find the line number of the object within its
  615.               file.
  616.  
  617.         Contained objects whose module does not match `module` are ignored.
  618.  
  619.         If `module` is False, no attempt to find the module will be made.
  620.         This is obscure, of use mostly in tests:  if `module` is False, or
  621.         is None but cannot be found automatically, then all objects are
  622.         considered to belong to the (non-existent) module, so all contained
  623.         objects will (recursively) be searched for doctests.
  624.  
  625.         The globals for each DocTest is formed by combining `globs`
  626.         and `extraglobs` (bindings in `extraglobs` override bindings
  627.         in `globs`).  A new copy of the globals dictionary is created
  628.         for each DocTest.  If `globs` is not specified, then it
  629.         defaults to the module's `__dict__`, if specified, or {}
  630.         otherwise.  If `extraglobs` is not specified, then it defaults
  631.         to {}.
  632.  
  633.         """
  634.         if name is None:
  635.             name = getattr(obj, '__name__', None)
  636.             if name is None:
  637.                 raise ValueError("DocTestFinder.find: name must be given when obj.__name__ doesn't exist: %r" % (type(obj),))
  638.             name is None
  639.         
  640.         if module is False:
  641.             module = None
  642.         elif module is None:
  643.             module = inspect.getmodule(obj)
  644.         
  645.         
  646.         try:
  647.             if not inspect.getsourcefile(obj):
  648.                 pass
  649.             file = inspect.getfile(obj)
  650.             if module is not None:
  651.                 source_lines = linecache.getlines(file, module.__dict__)
  652.             else:
  653.                 source_lines = linecache.getlines(file)
  654.             if not source_lines:
  655.                 source_lines = None
  656.         except TypeError:
  657.             source_lines = None
  658.  
  659.         if globs is None:
  660.             if module is None:
  661.                 globs = { }
  662.             else:
  663.                 globs = module.__dict__.copy()
  664.         else:
  665.             globs = globs.copy()
  666.         if extraglobs is not None:
  667.             globs.update(extraglobs)
  668.         
  669.         if '__name__' not in globs:
  670.             globs['__name__'] = '__main__'
  671.         
  672.         tests = []
  673.         self._find(tests, obj, name, module, source_lines, globs, { })
  674.         tests.sort()
  675.         return tests
  676.  
  677.     
  678.     def _from_module(self, module, object):
  679.         '''
  680.         Return true if the given object is defined in the given
  681.         module.
  682.         '''
  683.         if module is None:
  684.             return True
  685.         if inspect.getmodule(object) is not None:
  686.             return module is inspect.getmodule(object)
  687.         if inspect.isfunction(object):
  688.             return module.__dict__ is object.func_globals
  689.         if inspect.isclass(object):
  690.             return module.__name__ == object.__module__
  691.         if hasattr(object, '__module__'):
  692.             return module.__name__ == object.__module__
  693.         if isinstance(object, property):
  694.             return True
  695.         raise ValueError('object must be a class or function')
  696.  
  697.     
  698.     def _find(self, tests, obj, name, module, source_lines, globs, seen):
  699.         '''
  700.         Find tests for the given object and any contained objects, and
  701.         add them to `tests`.
  702.         '''
  703.         if self._verbose:
  704.             print 'Finding tests in %s' % name
  705.         
  706.         if id(obj) in seen:
  707.             return None
  708.         seen[id(obj)] = 1
  709.         test = self._get_test(obj, name, module, globs, source_lines)
  710.         if test is not None:
  711.             tests.append(test)
  712.         
  713.         if inspect.ismodule(obj) and self._recurse:
  714.             for valname, val in obj.__dict__.items():
  715.                 valname = '%s.%s' % (name, valname)
  716.                 if (inspect.isfunction(val) or inspect.isclass(val)) and self._from_module(module, val):
  717.                     self._find(tests, val, valname, module, source_lines, globs, seen)
  718.                     continue
  719.             
  720.         
  721.         if inspect.ismodule(obj) and self._recurse:
  722.             for valname, val in getattr(obj, '__test__', { }).items():
  723.                 if not isinstance(valname, basestring):
  724.                     raise ValueError('DocTestFinder.find: __test__ keys must be strings: %r' % (type(valname),))
  725.                 isinstance(valname, basestring)
  726.                 if not inspect.isfunction(val) and inspect.isclass(val) and inspect.ismethod(val) and inspect.ismodule(val) or isinstance(val, basestring):
  727.                     raise ValueError('DocTestFinder.find: __test__ values must be strings, functions, methods, classes, or modules: %r' % (type(val),))
  728.                 isinstance(val, basestring)
  729.                 valname = '%s.__test__.%s' % (name, valname)
  730.                 self._find(tests, val, valname, module, source_lines, globs, seen)
  731.             
  732.         
  733.         if inspect.isclass(obj) and self._recurse:
  734.             for valname, val in obj.__dict__.items():
  735.                 if isinstance(val, staticmethod):
  736.                     val = getattr(obj, valname)
  737.                 
  738.                 if isinstance(val, classmethod):
  739.                     val = getattr(obj, valname).im_func
  740.                 
  741.                 if (inspect.isfunction(val) and inspect.isclass(val) or isinstance(val, property)) and self._from_module(module, val):
  742.                     valname = '%s.%s' % (name, valname)
  743.                     self._find(tests, val, valname, module, source_lines, globs, seen)
  744.                     continue
  745.             
  746.         
  747.  
  748.     
  749.     def _get_test(self, obj, name, module, globs, source_lines):
  750.         '''
  751.         Return a DocTest for the given object, if it defines a docstring;
  752.         otherwise, return None.
  753.         '''
  754.         if isinstance(obj, basestring):
  755.             docstring = obj
  756.         else:
  757.             
  758.             try:
  759.                 if obj.__doc__ is None:
  760.                     docstring = ''
  761.                 else:
  762.                     docstring = obj.__doc__
  763.                     if not isinstance(docstring, basestring):
  764.                         docstring = str(docstring)
  765.             except (TypeError, AttributeError):
  766.                 docstring = ''
  767.             
  768.  
  769.         lineno = self._find_lineno(obj, source_lines)
  770.         if self._exclude_empty and not docstring:
  771.             return None
  772.         if module is None:
  773.             filename = None
  774.         else:
  775.             filename = getattr(module, '__file__', module.__name__)
  776.             if filename[-4:] in ('.pyc', '.pyo'):
  777.                 filename = filename[:-1]
  778.             
  779.         return self._parser.get_doctest(docstring, globs, name, filename, lineno)
  780.  
  781.     
  782.     def _find_lineno(self, obj, source_lines):
  783.         """
  784.         Return a line number of the given object's docstring.  Note:
  785.         this method assumes that the object has a docstring.
  786.         """
  787.         lineno = None
  788.         if inspect.ismodule(obj):
  789.             lineno = 0
  790.         
  791.         if inspect.isclass(obj):
  792.             if source_lines is None:
  793.                 return None
  794.             pat = re.compile('^\\s*class\\s*%s\\b' % getattr(obj, '__name__', '-'))
  795.             for i, line in enumerate(source_lines):
  796.                 if pat.match(line):
  797.                     lineno = i
  798.                     break
  799.                     continue
  800.                 source_lines is None
  801.             
  802.         
  803.         if inspect.ismethod(obj):
  804.             obj = obj.im_func
  805.         
  806.         if inspect.isfunction(obj):
  807.             obj = obj.func_code
  808.         
  809.         if inspect.istraceback(obj):
  810.             obj = obj.tb_frame
  811.         
  812.         if inspect.isframe(obj):
  813.             obj = obj.f_code
  814.         
  815.         if inspect.iscode(obj):
  816.             lineno = getattr(obj, 'co_firstlineno', None) - 1
  817.         
  818.  
  819.  
  820.  
  821. class DocTestRunner:
  822.     """
  823.     A class used to run DocTest test cases, and accumulate statistics.
  824.     The `run` method is used to process a single DocTest case.  It
  825.     returns a tuple `(f, t)`, where `t` is the number of test cases
  826.     tried, and `f` is the number of test cases that failed.
  827.  
  828.         >>> tests = DocTestFinder().find(_TestClass)
  829.         >>> runner = DocTestRunner(verbose=False)
  830.         >>> tests.sort(key = lambda test: test.name)
  831.         >>> for test in tests:
  832.         ...     print test.name, '->', runner.run(test)
  833.         _TestClass -> TestResults(failed=0, attempted=2)
  834.         _TestClass.__init__ -> TestResults(failed=0, attempted=2)
  835.         _TestClass.get -> TestResults(failed=0, attempted=2)
  836.         _TestClass.square -> TestResults(failed=0, attempted=1)
  837.  
  838.     The `summarize` method prints a summary of all the test cases that
  839.     have been run by the runner, and returns an aggregated `(f, t)`
  840.     tuple:
  841.  
  842.         >>> runner.summarize(verbose=1)
  843.         4 items passed all tests:
  844.            2 tests in _TestClass
  845.            2 tests in _TestClass.__init__
  846.            2 tests in _TestClass.get
  847.            1 tests in _TestClass.square
  848.         7 tests in 4 items.
  849.         7 passed and 0 failed.
  850.         Test passed.
  851.         TestResults(failed=0, attempted=7)
  852.  
  853.     The aggregated number of tried examples and failed examples is
  854.     also available via the `tries` and `failures` attributes:
  855.  
  856.         >>> runner.tries
  857.         7
  858.         >>> runner.failures
  859.         0
  860.  
  861.     The comparison between expected outputs and actual outputs is done
  862.     by an `OutputChecker`.  This comparison may be customized with a
  863.     number of option flags; see the documentation for `testmod` for
  864.     more information.  If the option flags are insufficient, then the
  865.     comparison may also be customized by passing a subclass of
  866.     `OutputChecker` to the constructor.
  867.  
  868.     The test runner's display output can be controlled in two ways.
  869.     First, an output function (`out) can be passed to
  870.     `TestRunner.run`; this function will be called with strings that
  871.     should be displayed.  It defaults to `sys.stdout.write`.  If
  872.     capturing the output is not sufficient, then the display output
  873.     can be also customized by subclassing DocTestRunner, and
  874.     overriding the methods `report_start`, `report_success`,
  875.     `report_unexpected_exception`, and `report_failure`.
  876.     """
  877.     DIVIDER = '*' * 70
  878.     
  879.     def __init__(self, checker = None, verbose = None, optionflags = 0):
  880.         """
  881.         Create a new test runner.
  882.  
  883.         Optional keyword arg `checker` is the `OutputChecker` that
  884.         should be used to compare the expected outputs and actual
  885.         outputs of doctest examples.
  886.  
  887.         Optional keyword arg 'verbose' prints lots of stuff if true,
  888.         only failures if false; by default, it's true iff '-v' is in
  889.         sys.argv.
  890.  
  891.         Optional argument `optionflags` can be used to control how the
  892.         test runner compares expected output to actual output, and how
  893.         it displays failures.  See the documentation for `testmod` for
  894.         more information.
  895.         """
  896.         if not checker:
  897.             pass
  898.         self._checker = OutputChecker()
  899.         if verbose is None:
  900.             verbose = '-v' in sys.argv
  901.         
  902.         self._verbose = verbose
  903.         self.optionflags = optionflags
  904.         self.original_optionflags = optionflags
  905.         self.tries = 0
  906.         self.failures = 0
  907.         self._name2ft = { }
  908.         self._fakeout = _SpoofOut()
  909.  
  910.     
  911.     def report_start(self, out, test, example):
  912.         '''
  913.         Report that the test runner is about to process the given
  914.         example.  (Only displays a message if verbose=True)
  915.         '''
  916.         if self._verbose:
  917.             if example.want:
  918.                 out('Trying:\n' + _indent(example.source) + 'Expecting:\n' + _indent(example.want))
  919.             else:
  920.                 out('Trying:\n' + _indent(example.source) + 'Expecting nothing\n')
  921.         
  922.  
  923.     
  924.     def report_success(self, out, test, example, got):
  925.         '''
  926.         Report that the given example ran successfully.  (Only
  927.         displays a message if verbose=True)
  928.         '''
  929.         if self._verbose:
  930.             out('ok\n')
  931.         
  932.  
  933.     
  934.     def report_failure(self, out, test, example, got):
  935.         '''
  936.         Report that the given example failed.
  937.         '''
  938.         out(self._failure_header(test, example) + self._checker.output_difference(example, got, self.optionflags))
  939.  
  940.     
  941.     def report_unexpected_exception(self, out, test, example, exc_info):
  942.         '''
  943.         Report that the given example raised an unexpected exception.
  944.         '''
  945.         out(self._failure_header(test, example) + 'Exception raised:\n' + _indent(_exception_traceback(exc_info)))
  946.  
  947.     
  948.     def _failure_header(self, test, example):
  949.         out = [
  950.             self.DIVIDER]
  951.         if test.filename:
  952.             if test.lineno is not None and example.lineno is not None:
  953.                 lineno = test.lineno + example.lineno + 1
  954.             else:
  955.                 lineno = '?'
  956.             out.append('File "%s", line %s, in %s' % (test.filename, lineno, test.name))
  957.         else:
  958.             out.append('Line %s, in %s' % (example.lineno + 1, test.name))
  959.         out.append('Failed example:')
  960.         source = example.source
  961.         out.append(_indent(source))
  962.         return '\n'.join(out)
  963.  
  964.     
  965.     def __run(self, test, compileflags, out):
  966.         '''
  967.         Run the examples in `test`.  Write the outcome of each example
  968.         with one of the `DocTestRunner.report_*` methods, using the
  969.         writer function `out`.  `compileflags` is the set of compiler
  970.         flags that should be used to execute examples.  Return a tuple
  971.         `(f, t)`, where `t` is the number of examples tried, and `f`
  972.         is the number of examples that failed.  The examples are run
  973.         in the namespace `test.globs`.
  974.         '''
  975.         failures = tries = 0
  976.         original_optionflags = self.optionflags
  977.         (SUCCESS, FAILURE, BOOM) = range(3)
  978.         check = self._checker.check_output
  979.         for examplenum, example in enumerate(test.examples):
  980.             if self.optionflags & REPORT_ONLY_FIRST_FAILURE:
  981.                 pass
  982.             quiet = failures > 0
  983.             self.optionflags = original_optionflags
  984.             if example.options:
  985.                 for optionflag, val in example.options.items():
  986.                     if val:
  987.                         self.optionflags |= optionflag
  988.                         continue
  989.                     self
  990.                     self.optionflags &= ~optionflag
  991.                 
  992.             
  993.             if self.optionflags & SKIP:
  994.                 continue
  995.             
  996.             tries += 1
  997.             if not quiet:
  998.                 self.report_start(out, test, example)
  999.             
  1000.             filename = '<doctest %s[%d]>' % (test.name, examplenum)
  1001.             
  1002.             try:
  1003.                 exec compile(example.source, filename, 'single', compileflags, 1) in test.globs
  1004.                 self.debugger.set_continue()
  1005.                 exception = None
  1006.             except KeyboardInterrupt:
  1007.                 raise 
  1008.             except:
  1009.                 exception = sys.exc_info()
  1010.                 self.debugger.set_continue()
  1011.  
  1012.             got = self._fakeout.getvalue()
  1013.             self._fakeout.truncate(0)
  1014.             outcome = FAILURE
  1015.             if exception is None:
  1016.                 if check(example.want, got, self.optionflags):
  1017.                     outcome = SUCCESS
  1018.                 
  1019.             else:
  1020.                 exc_info = sys.exc_info()
  1021.                 exc_msg = traceback.format_exception_only(*exc_info[:2])[-1]
  1022.                 if not quiet:
  1023.                     got += _exception_traceback(exc_info)
  1024.                 
  1025.                 if example.exc_msg is None:
  1026.                     outcome = BOOM
  1027.                 elif check(example.exc_msg, exc_msg, self.optionflags):
  1028.                     outcome = SUCCESS
  1029.                 elif self.optionflags & IGNORE_EXCEPTION_DETAIL:
  1030.                     m1 = re.match('[^:]*:', example.exc_msg)
  1031.                     m2 = re.match('[^:]*:', exc_msg)
  1032.                     if m1 and m2 and check(m1.group(0), m2.group(0), self.optionflags):
  1033.                         outcome = SUCCESS
  1034.                     
  1035.                 
  1036.             if outcome is SUCCESS:
  1037.                 if not quiet:
  1038.                     self.report_success(out, test, example, got)
  1039.                 
  1040.             quiet
  1041.             if outcome is FAILURE:
  1042.                 if not quiet:
  1043.                     self.report_failure(out, test, example, got)
  1044.                 
  1045.                 failures += 1
  1046.                 continue
  1047.             if outcome is BOOM:
  1048.                 if not quiet:
  1049.                     self.report_unexpected_exception(out, test, example, exc_info)
  1050.                 
  1051.                 failures += 1
  1052.                 continue
  1053.             if not False:
  1054.                 raise AssertionError, ('unknown outcome', outcome)
  1055.         
  1056.         self.optionflags = original_optionflags
  1057.         self._DocTestRunner__record_outcome(test, failures, tries)
  1058.         return TestResults(failures, tries)
  1059.  
  1060.     
  1061.     def __record_outcome(self, test, f, t):
  1062.         '''
  1063.         Record the fact that the given DocTest (`test`) generated `f`
  1064.         failures out of `t` tried examples.
  1065.         '''
  1066.         (f2, t2) = self._name2ft.get(test.name, (0, 0))
  1067.         self._name2ft[test.name] = (f + f2, t + t2)
  1068.         self.failures += f
  1069.         self.tries += t
  1070.  
  1071.     __LINECACHE_FILENAME_RE = re.compile('<doctest (?P<name>[\\w\\.]+)\\[(?P<examplenum>\\d+)\\]>$')
  1072.     
  1073.     def __patched_linecache_getlines(self, filename, module_globals = None):
  1074.         m = self._DocTestRunner__LINECACHE_FILENAME_RE.match(filename)
  1075.         if m and m.group('name') == self.test.name:
  1076.             example = self.test.examples[int(m.group('examplenum'))]
  1077.             return example.source.splitlines(True)
  1078.         return self.save_linecache_getlines(filename, module_globals)
  1079.  
  1080.     
  1081.     def run(self, test, compileflags = None, out = None, clear_globs = True):
  1082.         '''
  1083.         Run the examples in `test`, and display the results using the
  1084.         writer function `out`.
  1085.  
  1086.         The examples are run in the namespace `test.globs`.  If
  1087.         `clear_globs` is true (the default), then this namespace will
  1088.         be cleared after the test runs, to help with garbage
  1089.         collection.  If you would like to examine the namespace after
  1090.         the test completes, then use `clear_globs=False`.
  1091.  
  1092.         `compileflags` gives the set of flags that should be used by
  1093.         the Python compiler when running the examples.  If not
  1094.         specified, then it will default to the set of future-import
  1095.         flags that apply to `globs`.
  1096.  
  1097.         The output of each example is checked using
  1098.         `DocTestRunner.check_output`, and the results are formatted by
  1099.         the `DocTestRunner.report_*` methods.
  1100.         '''
  1101.         self.test = test
  1102.         if compileflags is None:
  1103.             compileflags = _extract_future_flags(test.globs)
  1104.         
  1105.         save_stdout = sys.stdout
  1106.         if out is None:
  1107.             out = save_stdout.write
  1108.         
  1109.         sys.stdout = self._fakeout
  1110.         save_set_trace = pdb.set_trace
  1111.         self.debugger = _OutputRedirectingPdb(save_stdout)
  1112.         self.debugger.reset()
  1113.         pdb.set_trace = self.debugger.set_trace
  1114.         self.save_linecache_getlines = linecache.getlines
  1115.         linecache.getlines = self._DocTestRunner__patched_linecache_getlines
  1116.         
  1117.         try:
  1118.             return self._DocTestRunner__run(test, compileflags, out)
  1119.         finally:
  1120.             sys.stdout = save_stdout
  1121.             pdb.set_trace = save_set_trace
  1122.             linecache.getlines = self.save_linecache_getlines
  1123.             if clear_globs:
  1124.                 test.globs.clear()
  1125.             
  1126.  
  1127.  
  1128.     
  1129.     def summarize(self, verbose = None):
  1130.         """
  1131.         Print a summary of all the test cases that have been run by
  1132.         this DocTestRunner, and return a tuple `(f, t)`, where `f` is
  1133.         the total number of failed examples, and `t` is the total
  1134.         number of tried examples.
  1135.  
  1136.         The optional `verbose` argument controls how detailed the
  1137.         summary is.  If the verbosity is not specified, then the
  1138.         DocTestRunner's verbosity is used.
  1139.         """
  1140.         if verbose is None:
  1141.             verbose = self._verbose
  1142.         
  1143.         notests = []
  1144.         passed = []
  1145.         failed = []
  1146.         totalt = totalf = 0
  1147.         for x in self._name2ft.items():
  1148.             (f, t) = (name,)
  1149.             if not f <= t:
  1150.                 raise AssertionError
  1151.             totalt += t
  1152.             totalf += f
  1153.             if t == 0:
  1154.                 notests.append(name)
  1155.                 continue
  1156.             f <= t
  1157.             if f == 0:
  1158.                 passed.append((name, t))
  1159.                 continue
  1160.             x
  1161.             failed.append(x)
  1162.         
  1163.         if verbose:
  1164.             if notests:
  1165.                 print len(notests), 'items had no tests:'
  1166.                 notests.sort()
  1167.                 for thing in notests:
  1168.                     print '   ', thing
  1169.                 
  1170.             
  1171.             if passed:
  1172.                 print len(passed), 'items passed all tests:'
  1173.                 passed.sort()
  1174.                 for thing, count in passed:
  1175.                     print ' %3d tests in %s' % (count, thing)
  1176.                 
  1177.             
  1178.         
  1179.         if failed:
  1180.             print self.DIVIDER
  1181.             print len(failed), 'items had failures:'
  1182.             failed.sort()
  1183.             for f, t in failed:
  1184.                 print ' %3d of %3d in %s' % (f, t, thing)
  1185.             
  1186.         
  1187.         if verbose:
  1188.             print totalt, 'tests in', len(self._name2ft), 'items.'
  1189.             print totalt - totalf, 'passed and', totalf, 'failed.'
  1190.         
  1191.         if totalf:
  1192.             print '***Test Failed***', totalf, 'failures.'
  1193.         elif verbose:
  1194.             print 'Test passed.'
  1195.         
  1196.         return TestResults(totalf, totalt)
  1197.  
  1198.     
  1199.     def merge(self, other):
  1200.         d = self._name2ft
  1201.         for f, t in other._name2ft.items():
  1202.             if name in d:
  1203.                 (f2, t2) = d[name]
  1204.                 f = f + f2
  1205.                 t = t + t2
  1206.             
  1207.             d[name] = (f, t)
  1208.         
  1209.  
  1210.  
  1211.  
  1212. class OutputChecker:
  1213.     '''
  1214.     A class used to check the whether the actual output from a doctest
  1215.     example matches the expected output.  `OutputChecker` defines two
  1216.     methods: `check_output`, which compares a given pair of outputs,
  1217.     and returns true if they match; and `output_difference`, which
  1218.     returns a string describing the differences between two outputs.
  1219.     '''
  1220.     
  1221.     def check_output(self, want, got, optionflags):
  1222.         '''
  1223.         Return True iff the actual output from an example (`got`)
  1224.         matches the expected output (`want`).  These strings are
  1225.         always considered to match if they are identical; but
  1226.         depending on what option flags the test runner is using,
  1227.         several non-exact match types are also possible.  See the
  1228.         documentation for `TestRunner` for more information about
  1229.         option flags.
  1230.         '''
  1231.         if got == want:
  1232.             return True
  1233.         return False
  1234.  
  1235.     
  1236.     def _do_a_fancy_diff(self, want, got, optionflags):
  1237.         if not optionflags & (REPORT_UDIFF | REPORT_CDIFF | REPORT_NDIFF):
  1238.             return False
  1239.         return optionflags & REPORT_NDIFF if optionflags & REPORT_NDIFF else got.count('\n') > 2
  1240.  
  1241.     
  1242.     def output_difference(self, example, got, optionflags):
  1243.         '''
  1244.         Return a string describing the differences between the
  1245.         expected output for a given example (`example`) and the actual
  1246.         output (`got`).  `optionflags` is the set of option flags used
  1247.         to compare `want` and `got`.
  1248.         '''
  1249.         want = example.want
  1250.         if not optionflags & DONT_ACCEPT_BLANKLINE:
  1251.             got = re.sub('(?m)^[ ]*(?=\n)', BLANKLINE_MARKER, got)
  1252.         
  1253.         if self._do_a_fancy_diff(want, got, optionflags):
  1254.             want_lines = want.splitlines(True)
  1255.             got_lines = got.splitlines(True)
  1256.             if optionflags & REPORT_UDIFF:
  1257.                 diff = difflib.unified_diff(want_lines, got_lines, n = 2)
  1258.                 diff = list(diff)[2:]
  1259.                 kind = 'unified diff with -expected +actual'
  1260.             elif optionflags & REPORT_CDIFF:
  1261.                 diff = difflib.context_diff(want_lines, got_lines, n = 2)
  1262.                 diff = list(diff)[2:]
  1263.                 kind = 'context diff with expected followed by actual'
  1264.             elif optionflags & REPORT_NDIFF:
  1265.                 engine = difflib.Differ(charjunk = difflib.IS_CHARACTER_JUNK)
  1266.                 diff = list(engine.compare(want_lines, got_lines))
  1267.                 kind = 'ndiff with -expected +actual'
  1268.             elif not 0:
  1269.                 raise AssertionError, 'Bad diff option'
  1270.             diff = [ line.rstrip() + '\n' for line in diff ]
  1271.             return 'Differences (%s):\n' % kind + _indent(''.join(diff))
  1272.         if want and got:
  1273.             return 'Expected:\n%sGot:\n%s' % (_indent(want), _indent(got))
  1274.         if want:
  1275.             return 'Expected:\n%sGot nothing\n' % _indent(want)
  1276.         if got:
  1277.             return 'Expected nothing\nGot:\n%s' % _indent(got)
  1278.         return 'Expected nothing\nGot nothing\n'
  1279.  
  1280.  
  1281.  
  1282. class DocTestFailure(Exception):
  1283.     '''A DocTest example has failed in debugging mode.
  1284.  
  1285.     The exception instance has variables:
  1286.  
  1287.     - test: the DocTest object being run
  1288.  
  1289.     - example: the Example object that failed
  1290.  
  1291.     - got: the actual output
  1292.     '''
  1293.     
  1294.     def __init__(self, test, example, got):
  1295.         self.test = test
  1296.         self.example = example
  1297.         self.got = got
  1298.  
  1299.     
  1300.     def __str__(self):
  1301.         return str(self.test)
  1302.  
  1303.  
  1304.  
  1305. class UnexpectedException(Exception):
  1306.     '''A DocTest example has encountered an unexpected exception
  1307.  
  1308.     The exception instance has variables:
  1309.  
  1310.     - test: the DocTest object being run
  1311.  
  1312.     - example: the Example object that failed
  1313.  
  1314.     - exc_info: the exception info
  1315.     '''
  1316.     
  1317.     def __init__(self, test, example, exc_info):
  1318.         self.test = test
  1319.         self.example = example
  1320.         self.exc_info = exc_info
  1321.  
  1322.     
  1323.     def __str__(self):
  1324.         return str(self.test)
  1325.  
  1326.  
  1327.  
  1328. class DebugRunner(DocTestRunner):
  1329.     """Run doc tests but raise an exception as soon as there is a failure.
  1330.  
  1331.        If an unexpected exception occurs, an UnexpectedException is raised.
  1332.        It contains the test, the example, and the original exception:
  1333.  
  1334.          >>> runner = DebugRunner(verbose=False)
  1335.          >>> test = DocTestParser().get_doctest('>>> raise KeyError\\n42',
  1336.          ...                                    {}, 'foo', 'foo.py', 0)
  1337.          >>> try:
  1338.          ...     runner.run(test)
  1339.          ... except UnexpectedException, failure:
  1340.          ...     pass
  1341.  
  1342.          >>> failure.test is test
  1343.          True
  1344.  
  1345.          >>> failure.example.want
  1346.          '42\\n'
  1347.  
  1348.          >>> exc_info = failure.exc_info
  1349.          >>> raise exc_info[0], exc_info[1], exc_info[2]
  1350.          Traceback (most recent call last):
  1351.          ...
  1352.          KeyError
  1353.  
  1354.        We wrap the original exception to give the calling application
  1355.        access to the test and example information.
  1356.  
  1357.        If the output doesn't match, then a DocTestFailure is raised:
  1358.  
  1359.          >>> test = DocTestParser().get_doctest('''
  1360.          ...      >>> x = 1
  1361.          ...      >>> x
  1362.          ...      2
  1363.          ...      ''', {}, 'foo', 'foo.py', 0)
  1364.  
  1365.          >>> try:
  1366.          ...    runner.run(test)
  1367.          ... except DocTestFailure, failure:
  1368.          ...    pass
  1369.  
  1370.        DocTestFailure objects provide access to the test:
  1371.  
  1372.          >>> failure.test is test
  1373.          True
  1374.  
  1375.        As well as to the example:
  1376.  
  1377.          >>> failure.example.want
  1378.          '2\\n'
  1379.  
  1380.        and the actual output:
  1381.  
  1382.          >>> failure.got
  1383.          '1\\n'
  1384.  
  1385.        If a failure or error occurs, the globals are left intact:
  1386.  
  1387.          >>> del test.globs['__builtins__']
  1388.          >>> test.globs
  1389.          {'x': 1}
  1390.  
  1391.          >>> test = DocTestParser().get_doctest('''
  1392.          ...      >>> x = 2
  1393.          ...      >>> raise KeyError
  1394.          ...      ''', {}, 'foo', 'foo.py', 0)
  1395.  
  1396.          >>> runner.run(test)
  1397.          Traceback (most recent call last):
  1398.          ...
  1399.          UnexpectedException: <DocTest foo from foo.py:0 (2 examples)>
  1400.  
  1401.          >>> del test.globs['__builtins__']
  1402.          >>> test.globs
  1403.          {'x': 2}
  1404.  
  1405.        But the globals are cleared if there is no error:
  1406.  
  1407.          >>> test = DocTestParser().get_doctest('''
  1408.          ...      >>> x = 2
  1409.          ...      ''', {}, 'foo', 'foo.py', 0)
  1410.  
  1411.          >>> runner.run(test)
  1412.          TestResults(failed=0, attempted=1)
  1413.  
  1414.          >>> test.globs
  1415.          {}
  1416.  
  1417.        """
  1418.     
  1419.     def run(self, test, compileflags = None, out = None, clear_globs = True):
  1420.         r = DocTestRunner.run(self, test, compileflags, out, False)
  1421.         if clear_globs:
  1422.             test.globs.clear()
  1423.         
  1424.         return r
  1425.  
  1426.     
  1427.     def report_unexpected_exception(self, out, test, example, exc_info):
  1428.         raise UnexpectedException(test, example, exc_info)
  1429.  
  1430.     
  1431.     def report_failure(self, out, test, example, got):
  1432.         raise DocTestFailure(test, example, got)
  1433.  
  1434.  
  1435. master = None
  1436.  
  1437. def testmod(m = None, name = None, globs = None, verbose = None, report = True, optionflags = 0, extraglobs = None, raise_on_error = False, exclude_empty = False):
  1438.     '''m=None, name=None, globs=None, verbose=None, report=True,
  1439.        optionflags=0, extraglobs=None, raise_on_error=False,
  1440.        exclude_empty=False
  1441.  
  1442.     Test examples in docstrings in functions and classes reachable
  1443.     from module m (or the current module if m is not supplied), starting
  1444.     with m.__doc__.
  1445.  
  1446.     Also test examples reachable from dict m.__test__ if it exists and is
  1447.     not None.  m.__test__ maps names to functions, classes and strings;
  1448.     function and class docstrings are tested even if the name is private;
  1449.     strings are tested directly, as if they were docstrings.
  1450.  
  1451.     Return (#failures, #tests).
  1452.  
  1453.     See doctest.__doc__ for an overview.
  1454.  
  1455.     Optional keyword arg "name" gives the name of the module; by default
  1456.     use m.__name__.
  1457.  
  1458.     Optional keyword arg "globs" gives a dict to be used as the globals
  1459.     when executing examples; by default, use m.__dict__.  A copy of this
  1460.     dict is actually used for each docstring, so that each docstring\'s
  1461.     examples start with a clean slate.
  1462.  
  1463.     Optional keyword arg "extraglobs" gives a dictionary that should be
  1464.     merged into the globals that are used to execute examples.  By
  1465.     default, no extra globals are used.  This is new in 2.4.
  1466.  
  1467.     Optional keyword arg "verbose" prints lots of stuff if true, prints
  1468.     only failures if false; by default, it\'s true iff "-v" is in sys.argv.
  1469.  
  1470.     Optional keyword arg "report" prints a summary at the end when true,
  1471.     else prints nothing at the end.  In verbose mode, the summary is
  1472.     detailed, else very brief (in fact, empty if all tests passed).
  1473.  
  1474.     Optional keyword arg "optionflags" or\'s together module constants,
  1475.     and defaults to 0.  This is new in 2.3.  Possible values (see the
  1476.     docs for details):
  1477.  
  1478.         DONT_ACCEPT_TRUE_FOR_1
  1479.         DONT_ACCEPT_BLANKLINE
  1480.         NORMALIZE_WHITESPACE
  1481.         ELLIPSIS
  1482.         SKIP
  1483.         IGNORE_EXCEPTION_DETAIL
  1484.         REPORT_UDIFF
  1485.         REPORT_CDIFF
  1486.         REPORT_NDIFF
  1487.         REPORT_ONLY_FIRST_FAILURE
  1488.  
  1489.     Optional keyword arg "raise_on_error" raises an exception on the
  1490.     first unexpected exception or failure. This allows failures to be
  1491.     post-mortem debugged.
  1492.  
  1493.     Advanced tomfoolery:  testmod runs methods of a local instance of
  1494.     class doctest.Tester, then merges the results into (or creates)
  1495.     global Tester instance doctest.master.  Methods of doctest.master
  1496.     can be called directly too, if you want to do something unusual.
  1497.     Passing report=0 to testmod is especially useful then, to delay
  1498.     displaying a summary.  Invoke doctest.master.summarize(verbose)
  1499.     when you\'re done fiddling.
  1500.     '''
  1501.     global master
  1502.     if m is None:
  1503.         m = sys.modules.get('__main__')
  1504.     
  1505.     if not inspect.ismodule(m):
  1506.         raise TypeError('testmod: module required; %r' % (m,))
  1507.     inspect.ismodule(m)
  1508.     if name is None:
  1509.         name = m.__name__
  1510.     
  1511.     finder = DocTestFinder(exclude_empty = exclude_empty)
  1512.     if raise_on_error:
  1513.         runner = DebugRunner(verbose = verbose, optionflags = optionflags)
  1514.     else:
  1515.         runner = DocTestRunner(verbose = verbose, optionflags = optionflags)
  1516.     for test in finder.find(m, name, globs = globs, extraglobs = extraglobs):
  1517.         runner.run(test)
  1518.     
  1519.     if report:
  1520.         runner.summarize()
  1521.     
  1522.     if master is None:
  1523.         master = runner
  1524.     else:
  1525.         master.merge(runner)
  1526.     return TestResults(runner.failures, runner.tries)
  1527.  
  1528.  
  1529. def testfile(filename, module_relative = True, name = None, package = None, globs = None, verbose = None, report = True, optionflags = 0, extraglobs = None, raise_on_error = False, parser = DocTestParser(), encoding = None):
  1530.     '''
  1531.     Test examples in the given file.  Return (#failures, #tests).
  1532.  
  1533.     Optional keyword arg "module_relative" specifies how filenames
  1534.     should be interpreted:
  1535.  
  1536.       - If "module_relative" is True (the default), then "filename"
  1537.          specifies a module-relative path.  By default, this path is
  1538.          relative to the calling module\'s directory; but if the
  1539.          "package" argument is specified, then it is relative to that
  1540.          package.  To ensure os-independence, "filename" should use
  1541.          "/" characters to separate path segments, and should not
  1542.          be an absolute path (i.e., it may not begin with "/").
  1543.  
  1544.       - If "module_relative" is False, then "filename" specifies an
  1545.         os-specific path.  The path may be absolute or relative (to
  1546.         the current working directory).
  1547.  
  1548.     Optional keyword arg "name" gives the name of the test; by default
  1549.     use the file\'s basename.
  1550.  
  1551.     Optional keyword argument "package" is a Python package or the
  1552.     name of a Python package whose directory should be used as the
  1553.     base directory for a module relative filename.  If no package is
  1554.     specified, then the calling module\'s directory is used as the base
  1555.     directory for module relative filenames.  It is an error to
  1556.     specify "package" if "module_relative" is False.
  1557.  
  1558.     Optional keyword arg "globs" gives a dict to be used as the globals
  1559.     when executing examples; by default, use {}.  A copy of this dict
  1560.     is actually used for each docstring, so that each docstring\'s
  1561.     examples start with a clean slate.
  1562.  
  1563.     Optional keyword arg "extraglobs" gives a dictionary that should be
  1564.     merged into the globals that are used to execute examples.  By
  1565.     default, no extra globals are used.
  1566.  
  1567.     Optional keyword arg "verbose" prints lots of stuff if true, prints
  1568.     only failures if false; by default, it\'s true iff "-v" is in sys.argv.
  1569.  
  1570.     Optional keyword arg "report" prints a summary at the end when true,
  1571.     else prints nothing at the end.  In verbose mode, the summary is
  1572.     detailed, else very brief (in fact, empty if all tests passed).
  1573.  
  1574.     Optional keyword arg "optionflags" or\'s together module constants,
  1575.     and defaults to 0.  Possible values (see the docs for details):
  1576.  
  1577.         DONT_ACCEPT_TRUE_FOR_1
  1578.         DONT_ACCEPT_BLANKLINE
  1579.         NORMALIZE_WHITESPACE
  1580.         ELLIPSIS
  1581.         SKIP
  1582.         IGNORE_EXCEPTION_DETAIL
  1583.         REPORT_UDIFF
  1584.         REPORT_CDIFF
  1585.         REPORT_NDIFF
  1586.         REPORT_ONLY_FIRST_FAILURE
  1587.  
  1588.     Optional keyword arg "raise_on_error" raises an exception on the
  1589.     first unexpected exception or failure. This allows failures to be
  1590.     post-mortem debugged.
  1591.  
  1592.     Optional keyword arg "parser" specifies a DocTestParser (or
  1593.     subclass) that should be used to extract tests from the files.
  1594.  
  1595.     Optional keyword arg "encoding" specifies an encoding that should
  1596.     be used to convert the file to unicode.
  1597.  
  1598.     Advanced tomfoolery:  testmod runs methods of a local instance of
  1599.     class doctest.Tester, then merges the results into (or creates)
  1600.     global Tester instance doctest.master.  Methods of doctest.master
  1601.     can be called directly too, if you want to do something unusual.
  1602.     Passing report=0 to testmod is especially useful then, to delay
  1603.     displaying a summary.  Invoke doctest.master.summarize(verbose)
  1604.     when you\'re done fiddling.
  1605.     '''
  1606.     global master
  1607.     if package and not module_relative:
  1608.         raise ValueError('Package may only be specified for module-relative paths.')
  1609.     not module_relative
  1610.     (text, filename) = _load_testfile(filename, package, module_relative)
  1611.     if name is None:
  1612.         name = os.path.basename(filename)
  1613.     
  1614.     if globs is None:
  1615.         globs = { }
  1616.     else:
  1617.         globs = globs.copy()
  1618.     if extraglobs is not None:
  1619.         globs.update(extraglobs)
  1620.     
  1621.     if '__name__' not in globs:
  1622.         globs['__name__'] = '__main__'
  1623.     
  1624.     if raise_on_error:
  1625.         runner = DebugRunner(verbose = verbose, optionflags = optionflags)
  1626.     else:
  1627.         runner = DocTestRunner(verbose = verbose, optionflags = optionflags)
  1628.     if encoding is not None:
  1629.         text = text.decode(encoding)
  1630.     
  1631.     test = parser.get_doctest(text, globs, name, filename, 0)
  1632.     runner.run(test)
  1633.     if report:
  1634.         runner.summarize()
  1635.     
  1636.     if master is None:
  1637.         master = runner
  1638.     else:
  1639.         master.merge(runner)
  1640.     return TestResults(runner.failures, runner.tries)
  1641.  
  1642.  
  1643. def run_docstring_examples(f, globs, verbose = False, name = 'NoName', compileflags = None, optionflags = 0):
  1644.     """
  1645.     Test examples in the given object's docstring (`f`), using `globs`
  1646.     as globals.  Optional argument `name` is used in failure messages.
  1647.     If the optional argument `verbose` is true, then generate output
  1648.     even if there are no failures.
  1649.  
  1650.     `compileflags` gives the set of flags that should be used by the
  1651.     Python compiler when running the examples.  If not specified, then
  1652.     it will default to the set of future-import flags that apply to
  1653.     `globs`.
  1654.  
  1655.     Optional keyword arg `optionflags` specifies options for the
  1656.     testing and output.  See the documentation for `testmod` for more
  1657.     information.
  1658.     """
  1659.     finder = DocTestFinder(verbose = verbose, recurse = False)
  1660.     runner = DocTestRunner(verbose = verbose, optionflags = optionflags)
  1661.     for test in finder.find(f, name, globs = globs):
  1662.         runner.run(test, compileflags = compileflags)
  1663.     
  1664.  
  1665.  
  1666. class Tester:
  1667.     
  1668.     def __init__(self, mod = None, globs = None, verbose = None, optionflags = 0):
  1669.         warnings.warn('class Tester is deprecated; use class doctest.DocTestRunner instead', DeprecationWarning, stacklevel = 2)
  1670.         if mod is None and globs is None:
  1671.             raise TypeError('Tester.__init__: must specify mod or globs')
  1672.         globs is None
  1673.         if mod is not None and not inspect.ismodule(mod):
  1674.             raise TypeError('Tester.__init__: mod must be a module; %r' % (mod,))
  1675.         not inspect.ismodule(mod)
  1676.         if globs is None:
  1677.             globs = mod.__dict__
  1678.         
  1679.         self.globs = globs
  1680.         self.verbose = verbose
  1681.         self.optionflags = optionflags
  1682.         self.testfinder = DocTestFinder()
  1683.         self.testrunner = DocTestRunner(verbose = verbose, optionflags = optionflags)
  1684.  
  1685.     
  1686.     def runstring(self, s, name):
  1687.         test = DocTestParser().get_doctest(s, self.globs, name, None, None)
  1688.         if self.verbose:
  1689.             print 'Running string', name
  1690.         
  1691.         (f, t) = self.testrunner.run(test)
  1692.         if self.verbose:
  1693.             print f, 'of', t, 'examples failed in string', name
  1694.         
  1695.         return TestResults(f, t)
  1696.  
  1697.     
  1698.     def rundoc(self, object, name = None, module = None):
  1699.         f = t = 0
  1700.         tests = self.testfinder.find(object, name, module = module, globs = self.globs)
  1701.         for test in tests:
  1702.             (f2, t2) = self.testrunner.run(test)
  1703.             f = f + f2
  1704.             t = t + t2
  1705.         
  1706.         return TestResults(f, t)
  1707.  
  1708.     
  1709.     def rundict(self, d, name, module = None):
  1710.         import types as types
  1711.         m = types.ModuleType(name)
  1712.         m.__dict__.update(d)
  1713.         if module is None:
  1714.             module = False
  1715.         
  1716.         return self.rundoc(m, name, module)
  1717.  
  1718.     
  1719.     def run__test__(self, d, name):
  1720.         import types
  1721.         m = types.ModuleType(name)
  1722.         m.__test__ = d
  1723.         return self.rundoc(m, name)
  1724.  
  1725.     
  1726.     def summarize(self, verbose = None):
  1727.         return self.testrunner.summarize(verbose)
  1728.  
  1729.     
  1730.     def merge(self, other):
  1731.         self.testrunner.merge(other.testrunner)
  1732.  
  1733.  
  1734. _unittest_reportflags = 0
  1735.  
  1736. def set_unittest_reportflags(flags):
  1737.     """Sets the unittest option flags.
  1738.  
  1739.     The old flag is returned so that a runner could restore the old
  1740.     value if it wished to:
  1741.  
  1742.       >>> import doctest
  1743.       >>> old = doctest._unittest_reportflags
  1744.       >>> doctest.set_unittest_reportflags(REPORT_NDIFF |
  1745.       ...                          REPORT_ONLY_FIRST_FAILURE) == old
  1746.       True
  1747.  
  1748.       >>> doctest._unittest_reportflags == (REPORT_NDIFF |
  1749.       ...                                   REPORT_ONLY_FIRST_FAILURE)
  1750.       True
  1751.  
  1752.     Only reporting flags can be set:
  1753.  
  1754.       >>> doctest.set_unittest_reportflags(ELLIPSIS)
  1755.       Traceback (most recent call last):
  1756.       ...
  1757.       ValueError: ('Only reporting flags allowed', 8)
  1758.  
  1759.       >>> doctest.set_unittest_reportflags(old) == (REPORT_NDIFF |
  1760.       ...                                   REPORT_ONLY_FIRST_FAILURE)
  1761.       True
  1762.     """
  1763.     global _unittest_reportflags
  1764.     if flags & REPORTING_FLAGS != flags:
  1765.         raise ValueError('Only reporting flags allowed', flags)
  1766.     flags & REPORTING_FLAGS != flags
  1767.     old = _unittest_reportflags
  1768.     _unittest_reportflags = flags
  1769.     return old
  1770.  
  1771.  
  1772. class DocTestCase(unittest.TestCase):
  1773.     
  1774.     def __init__(self, test, optionflags = 0, setUp = None, tearDown = None, checker = None):
  1775.         unittest.TestCase.__init__(self)
  1776.         self._dt_optionflags = optionflags
  1777.         self._dt_checker = checker
  1778.         self._dt_test = test
  1779.         self._dt_setUp = setUp
  1780.         self._dt_tearDown = tearDown
  1781.  
  1782.     
  1783.     def setUp(self):
  1784.         test = self._dt_test
  1785.         if self._dt_setUp is not None:
  1786.             self._dt_setUp(test)
  1787.         
  1788.  
  1789.     
  1790.     def tearDown(self):
  1791.         test = self._dt_test
  1792.         if self._dt_tearDown is not None:
  1793.             self._dt_tearDown(test)
  1794.         
  1795.         test.globs.clear()
  1796.  
  1797.     
  1798.     def runTest(self):
  1799.         test = self._dt_test
  1800.         old = sys.stdout
  1801.         new = StringIO()
  1802.         optionflags = self._dt_optionflags
  1803.         if not optionflags & REPORTING_FLAGS:
  1804.             optionflags |= _unittest_reportflags
  1805.         
  1806.         runner = DocTestRunner(optionflags = optionflags, checker = self._dt_checker, verbose = False)
  1807.         
  1808.         try:
  1809.             runner.DIVIDER = '-' * 70
  1810.             (failures, tries) = runner.run(test, out = new.write, clear_globs = False)
  1811.         finally:
  1812.             sys.stdout = old
  1813.  
  1814.         if failures:
  1815.             raise self.failureException(self.format_failure(new.getvalue()))
  1816.         failures
  1817.  
  1818.     
  1819.     def format_failure(self, err):
  1820.         test = self._dt_test
  1821.         if test.lineno is None:
  1822.             lineno = 'unknown line number'
  1823.         else:
  1824.             lineno = '%s' % test.lineno
  1825.         lname = '.'.join(test.name.split('.')[-1:])
  1826.         return 'Failed doctest test for %s\n  File "%s", line %s, in %s\n\n%s' % (test.name, test.filename, lineno, lname, err)
  1827.  
  1828.     
  1829.     def debug(self):
  1830.         """Run the test case without results and without catching exceptions
  1831.  
  1832.            The unit test framework includes a debug method on test cases
  1833.            and test suites to support post-mortem debugging.  The test code
  1834.            is run in such a way that errors are not caught.  This way a
  1835.            caller can catch the errors and initiate post-mortem debugging.
  1836.  
  1837.            The DocTestCase provides a debug method that raises
  1838.            UnexpectedException errors if there is an unexepcted
  1839.            exception:
  1840.  
  1841.              >>> test = DocTestParser().get_doctest('>>> raise KeyError\\n42',
  1842.              ...                {}, 'foo', 'foo.py', 0)
  1843.              >>> case = DocTestCase(test)
  1844.              >>> try:
  1845.              ...     case.debug()
  1846.              ... except UnexpectedException, failure:
  1847.              ...     pass
  1848.  
  1849.            The UnexpectedException contains the test, the example, and
  1850.            the original exception:
  1851.  
  1852.              >>> failure.test is test
  1853.              True
  1854.  
  1855.              >>> failure.example.want
  1856.              '42\\n'
  1857.  
  1858.              >>> exc_info = failure.exc_info
  1859.              >>> raise exc_info[0], exc_info[1], exc_info[2]
  1860.              Traceback (most recent call last):
  1861.              ...
  1862.              KeyError
  1863.  
  1864.            If the output doesn't match, then a DocTestFailure is raised:
  1865.  
  1866.              >>> test = DocTestParser().get_doctest('''
  1867.              ...      >>> x = 1
  1868.              ...      >>> x
  1869.              ...      2
  1870.              ...      ''', {}, 'foo', 'foo.py', 0)
  1871.              >>> case = DocTestCase(test)
  1872.  
  1873.              >>> try:
  1874.              ...    case.debug()
  1875.              ... except DocTestFailure, failure:
  1876.              ...    pass
  1877.  
  1878.            DocTestFailure objects provide access to the test:
  1879.  
  1880.              >>> failure.test is test
  1881.              True
  1882.  
  1883.            As well as to the example:
  1884.  
  1885.              >>> failure.example.want
  1886.              '2\\n'
  1887.  
  1888.            and the actual output:
  1889.  
  1890.              >>> failure.got
  1891.              '1\\n'
  1892.  
  1893.            """
  1894.         self.setUp()
  1895.         runner = DebugRunner(optionflags = self._dt_optionflags, checker = self._dt_checker, verbose = False)
  1896.         runner.run(self._dt_test, clear_globs = False)
  1897.         self.tearDown()
  1898.  
  1899.     
  1900.     def id(self):
  1901.         return self._dt_test.name
  1902.  
  1903.     
  1904.     def __repr__(self):
  1905.         name = self._dt_test.name.split('.')
  1906.         return '%s (%s)' % (name[-1], '.'.join(name[:-1]))
  1907.  
  1908.     __str__ = __repr__
  1909.     
  1910.     def shortDescription(self):
  1911.         return 'Doctest: ' + self._dt_test.name
  1912.  
  1913.  
  1914.  
  1915. def DocTestSuite(module = None, globs = None, extraglobs = None, test_finder = None, **options):
  1916.     '''
  1917.     Convert doctest tests for a module to a unittest test suite.
  1918.  
  1919.     This converts each documentation string in a module that
  1920.     contains doctest tests to a unittest test case.  If any of the
  1921.     tests in a doc string fail, then the test case fails.  An exception
  1922.     is raised showing the name of the file containing the test and a
  1923.     (sometimes approximate) line number.
  1924.  
  1925.     The `module` argument provides the module to be tested.  The argument
  1926.     can be either a module or a module name.
  1927.  
  1928.     If no argument is given, the calling module is used.
  1929.  
  1930.     A number of options may be provided as keyword arguments:
  1931.  
  1932.     setUp
  1933.       A set-up function.  This is called before running the
  1934.       tests in each file. The setUp function will be passed a DocTest
  1935.       object.  The setUp function can access the test globals as the
  1936.       globs attribute of the test passed.
  1937.  
  1938.     tearDown
  1939.       A tear-down function.  This is called after running the
  1940.       tests in each file.  The tearDown function will be passed a DocTest
  1941.       object.  The tearDown function can access the test globals as the
  1942.       globs attribute of the test passed.
  1943.  
  1944.     globs
  1945.       A dictionary containing initial global variables for the tests.
  1946.  
  1947.     optionflags
  1948.        A set of doctest option flags expressed as an integer.
  1949.     '''
  1950.     if test_finder is None:
  1951.         test_finder = DocTestFinder()
  1952.     
  1953.     module = _normalize_module(module)
  1954.     tests = test_finder.find(module, globs = globs, extraglobs = extraglobs)
  1955.     if not tests:
  1956.         raise ValueError(module, 'has no tests')
  1957.     tests
  1958.     tests.sort()
  1959.     suite = unittest.TestSuite()
  1960.     for test in tests:
  1961.         if len(test.examples) == 0:
  1962.             continue
  1963.         
  1964.         if not test.filename:
  1965.             filename = module.__file__
  1966.             if filename[-4:] in ('.pyc', '.pyo'):
  1967.                 filename = filename[:-1]
  1968.             
  1969.             test.filename = filename
  1970.         
  1971.         suite.addTest(DocTestCase(test, **options))
  1972.     
  1973.     return suite
  1974.  
  1975.  
  1976. class DocFileCase(DocTestCase):
  1977.     
  1978.     def id(self):
  1979.         return '_'.join(self._dt_test.name.split('.'))
  1980.  
  1981.     
  1982.     def __repr__(self):
  1983.         return self._dt_test.filename
  1984.  
  1985.     __str__ = __repr__
  1986.     
  1987.     def format_failure(self, err):
  1988.         return 'Failed doctest test for %s\n  File "%s", line 0\n\n%s' % (self._dt_test.name, self._dt_test.filename, err)
  1989.  
  1990.  
  1991.  
  1992. def DocFileTest(path, module_relative = True, package = None, globs = None, parser = DocTestParser(), encoding = None, **options):
  1993.     if globs is None:
  1994.         globs = { }
  1995.     else:
  1996.         globs = globs.copy()
  1997.     if package and not module_relative:
  1998.         raise ValueError('Package may only be specified for module-relative paths.')
  1999.     not module_relative
  2000.     (doc, path) = _load_testfile(path, package, module_relative)
  2001.     if '__file__' not in globs:
  2002.         globs['__file__'] = path
  2003.     
  2004.     name = os.path.basename(path)
  2005.     if encoding is not None:
  2006.         doc = doc.decode(encoding)
  2007.     
  2008.     test = parser.get_doctest(doc, globs, name, path, 0)
  2009.     return DocFileCase(test, **options)
  2010.  
  2011.  
  2012. def DocFileSuite(*paths, **kw):
  2013.     '''A unittest suite for one or more doctest files.
  2014.  
  2015.     The path to each doctest file is given as a string; the
  2016.     interpretation of that string depends on the keyword argument
  2017.     "module_relative".
  2018.  
  2019.     A number of options may be provided as keyword arguments:
  2020.  
  2021.     module_relative
  2022.       If "module_relative" is True, then the given file paths are
  2023.       interpreted as os-independent module-relative paths.  By
  2024.       default, these paths are relative to the calling module\'s
  2025.       directory; but if the "package" argument is specified, then
  2026.       they are relative to that package.  To ensure os-independence,
  2027.       "filename" should use "/" characters to separate path
  2028.       segments, and may not be an absolute path (i.e., it may not
  2029.       begin with "/").
  2030.  
  2031.       If "module_relative" is False, then the given file paths are
  2032.       interpreted as os-specific paths.  These paths may be absolute
  2033.       or relative (to the current working directory).
  2034.  
  2035.     package
  2036.       A Python package or the name of a Python package whose directory
  2037.       should be used as the base directory for module relative paths.
  2038.       If "package" is not specified, then the calling module\'s
  2039.       directory is used as the base directory for module relative
  2040.       filenames.  It is an error to specify "package" if
  2041.       "module_relative" is False.
  2042.  
  2043.     setUp
  2044.       A set-up function.  This is called before running the
  2045.       tests in each file. The setUp function will be passed a DocTest
  2046.       object.  The setUp function can access the test globals as the
  2047.       globs attribute of the test passed.
  2048.  
  2049.     tearDown
  2050.       A tear-down function.  This is called after running the
  2051.       tests in each file.  The tearDown function will be passed a DocTest
  2052.       object.  The tearDown function can access the test globals as the
  2053.       globs attribute of the test passed.
  2054.  
  2055.     globs
  2056.       A dictionary containing initial global variables for the tests.
  2057.  
  2058.     optionflags
  2059.       A set of doctest option flags expressed as an integer.
  2060.  
  2061.     parser
  2062.       A DocTestParser (or subclass) that should be used to extract
  2063.       tests from the files.
  2064.  
  2065.     encoding
  2066.       An encoding that will be used to convert the files to unicode.
  2067.     '''
  2068.     suite = unittest.TestSuite()
  2069.     if kw.get('module_relative', True):
  2070.         kw['package'] = _normalize_module(kw.get('package'))
  2071.     
  2072.     for path in paths:
  2073.         suite.addTest(DocFileTest(path, **kw))
  2074.     
  2075.     return suite
  2076.  
  2077.  
  2078. def script_from_examples(s):
  2079.     """Extract script from text with examples.
  2080.  
  2081.        Converts text with examples to a Python script.  Example input is
  2082.        converted to regular code.  Example output and all other words
  2083.        are converted to comments:
  2084.  
  2085.        >>> text = '''
  2086.        ...       Here are examples of simple math.
  2087.        ...
  2088.        ...           Python has super accurate integer addition
  2089.        ...
  2090.        ...           >>> 2 + 2
  2091.        ...           5
  2092.        ...
  2093.        ...           And very friendly error messages:
  2094.        ...
  2095.        ...           >>> 1/0
  2096.        ...           To Infinity
  2097.        ...           And
  2098.        ...           Beyond
  2099.        ...
  2100.        ...           You can use logic if you want:
  2101.        ...
  2102.        ...           >>> if 0:
  2103.        ...           ...    blah
  2104.        ...           ...    blah
  2105.        ...           ...
  2106.        ...
  2107.        ...           Ho hum
  2108.        ...           '''
  2109.  
  2110.        >>> print script_from_examples(text)
  2111.        # Here are examples of simple math.
  2112.        #
  2113.        #     Python has super accurate integer addition
  2114.        #
  2115.        2 + 2
  2116.        # Expected:
  2117.        ## 5
  2118.        #
  2119.        #     And very friendly error messages:
  2120.        #
  2121.        1/0
  2122.        # Expected:
  2123.        ## To Infinity
  2124.        ## And
  2125.        ## Beyond
  2126.        #
  2127.        #     You can use logic if you want:
  2128.        #
  2129.        if 0:
  2130.           blah
  2131.           blah
  2132.        #
  2133.        #     Ho hum
  2134.        <BLANKLINE>
  2135.        """
  2136.     output = []
  2137.     for piece in DocTestParser().parse(s):
  2138.         if isinstance(piece, Example):
  2139.             output.append(piece.source[:-1])
  2140.             want = piece.want
  2141.             if want:
  2142.                 output.append('# Expected:')
  2143.                 [] += [ '## ' + l for l in want.split('\n')[:-1] ]
  2144.             
  2145.         want
  2146.         [] += [ _comment_line(l) for l in piece.split('\n')[:-1] ]
  2147.     
  2148.     while output and output[-1] == '#':
  2149.         output.pop()
  2150.         continue
  2151.         []
  2152.     while output and output[0] == '#':
  2153.         output.pop(0)
  2154.         continue
  2155.         output
  2156.     return '\n'.join(output) + '\n'
  2157.  
  2158.  
  2159. def testsource(module, name):
  2160.     '''Extract the test sources from a doctest docstring as a script.
  2161.  
  2162.     Provide the module (or dotted name of the module) containing the
  2163.     test to be debugged and the name (within the module) of the object
  2164.     with the doc string with tests to be debugged.
  2165.     '''
  2166.     module = _normalize_module(module)
  2167.     tests = DocTestFinder().find(module)
  2168.     test = _[1]
  2169.     if not test:
  2170.         raise ValueError(name, 'not found in tests')
  2171.     test
  2172.     test = test[0]
  2173.     testsrc = script_from_examples(test.docstring)
  2174.     return testsrc
  2175.  
  2176.  
  2177. def debug_src(src, pm = False, globs = None):
  2178.     """Debug a single doctest docstring, in argument `src`'"""
  2179.     testsrc = script_from_examples(src)
  2180.     debug_script(testsrc, pm, globs)
  2181.  
  2182.  
  2183. def debug_script(src, pm = False, globs = None):
  2184.     '''Debug a test script.  `src` is the script, as a string.'''
  2185.     import pdb
  2186.     srcfilename = tempfile.mktemp('.py', 'doctestdebug')
  2187.     f = open(srcfilename, 'w')
  2188.     f.write(src)
  2189.     f.close()
  2190.     
  2191.     try:
  2192.         if globs:
  2193.             globs = globs.copy()
  2194.         else:
  2195.             globs = { }
  2196.         if pm:
  2197.             
  2198.             try:
  2199.                 execfile(srcfilename, globs, globs)
  2200.             print sys.exc_info()[1]
  2201.             pdb.post_mortem(sys.exc_info()[2])
  2202.  
  2203.         else:
  2204.             pdb.run('execfile(%r)' % srcfilename, globs, globs)
  2205.     finally:
  2206.         os.remove(srcfilename)
  2207.  
  2208.  
  2209.  
  2210. def debug(module, name, pm = False):
  2211.     '''Debug a single doctest docstring.
  2212.  
  2213.     Provide the module (or dotted name of the module) containing the
  2214.     test to be debugged and the name (within the module) of the object
  2215.     with the docstring with tests to be debugged.
  2216.     '''
  2217.     module = _normalize_module(module)
  2218.     testsrc = testsource(module, name)
  2219.     debug_script(testsrc, pm, module.__dict__)
  2220.  
  2221.  
  2222. class _TestClass:
  2223.     """
  2224.     A pointless class, for sanity-checking of docstring testing.
  2225.  
  2226.     Methods:
  2227.         square()
  2228.         get()
  2229.  
  2230.     >>> _TestClass(13).get() + _TestClass(-12).get()
  2231.     1
  2232.     >>> hex(_TestClass(13).square().get())
  2233.     '0xa9'
  2234.     """
  2235.     
  2236.     def __init__(self, val):
  2237.         '''val -> _TestClass object with associated value val.
  2238.  
  2239.         >>> t = _TestClass(123)
  2240.         >>> print t.get()
  2241.         123
  2242.         '''
  2243.         self.val = val
  2244.  
  2245.     
  2246.     def square(self):
  2247.         """square() -> square TestClass's associated value
  2248.  
  2249.         >>> _TestClass(13).square().get()
  2250.         169
  2251.         """
  2252.         self.val = self.val ** 2
  2253.         return self
  2254.  
  2255.     
  2256.     def get(self):
  2257.         """get() -> return TestClass's associated value.
  2258.  
  2259.         >>> x = _TestClass(-42)
  2260.         >>> print x.get()
  2261.         -42
  2262.         """
  2263.         return self.val
  2264.  
  2265.  
  2266. __test__ = {
  2267.     '_TestClass': _TestClass,
  2268.     'string': '\n                      Example of a string object, searched as-is.\n                      >>> x = 1; y = 2\n                      >>> x + y, x * y\n                      (3, 2)\n                      ',
  2269.     'bool-int equivalence': '\n                                    In 2.2, boolean expressions displayed\n                                    0 or 1.  By default, we still accept\n                                    them.  This can be disabled by passing\n                                    DONT_ACCEPT_TRUE_FOR_1 to the new\n                                    optionflags argument.\n                                    >>> 4 == 4\n                                    1\n                                    >>> 4 == 4\n                                    True\n                                    >>> 4 > 4\n                                    0\n                                    >>> 4 > 4\n                                    False\n                                    ',
  2270.     'blank lines': "\n                Blank lines can be marked with <BLANKLINE>:\n                    >>> print 'foo\\n\\nbar\\n'\n                    foo\n                    <BLANKLINE>\n                    bar\n                    <BLANKLINE>\n            ",
  2271.     'ellipsis': "\n                If the ellipsis flag is used, then '...' can be used to\n                elide substrings in the desired output:\n                    >>> print range(1000) #doctest: +ELLIPSIS\n                    [0, 1, 2, ..., 999]\n            ",
  2272.     'whitespace normalization': '\n                If the whitespace normalization flag is used, then\n                differences in whitespace are ignored.\n                    >>> print range(30) #doctest: +NORMALIZE_WHITESPACE\n                    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,\n                     15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,\n                     27, 28, 29]\n            ' }
  2273.  
  2274. def _test():
  2275.     testfiles = _[1]
  2276.     return 0
  2277.  
  2278. if __name__ == '__main__':
  2279.     sys.exit(_test())
  2280.  
  2281.